<?php
$course_id = isset($_GET["course_id"]) ? $_GET["course_id"] : null;
switch ($_SERVER['REQUEST_METHOD']) {
	case 'GET':
		edit_course_GET($course_id);
		break;
	
	case 'POST':
		edit_course_POST();
		break;
	default:
		break;
}

function edit_course_GET($course_id) {
	global $woodb;
	$courses = $woodb->getCourseByID($course_id);
	$course = $courses[0];
	$year = date("Y");
	?>
	<script type="text/javascript">document.body.className = document.body.className.replace('no-js','js');</script>
	<div class="wrap">
		<h2>Edit Course</h2>
		<div class='woo_breadcrumbs'>
		<a href='?page=woodle_admin'>Courses</a> &raquo; 
		Edit Course
		</div>
		<form method="post" action="admin.php?page=woodle_admin&action=woodle_edit_course&course_id=<?=$course_id?>">
			<input type="hidden" name="course_id" id="course_id" value="<?=$course->course_id?>" />
			<div id="titlediv">
				<div id="titlewrap">
					<div style="float:left; margin-right: 20px">
						<h3>Course Name</h3>
						<input type="text" autocomplete="off" id="title" value="<?=$course->name ?>" tabindex="1" size="30" name="course_title">
					</div>
					<div style="float:left;  margin-right: 20px">
						<h3>Semester</h3>
						<select name="course_semester">
							<option  <?= (($course->semester == "SS") ? "selected='selected'" : "") ?>  value="SS">Spring Semester</option>
							<option  <?= (($course->semester == "FS") ? "selected='selected'" : "") ?>  value="FS">Fall Semester</option>
						</select>	
					</div>
					<div style="float:left">
						<h3>Year</h3>
						<select name="course_year">
							<?php
							for($y=$year;$y<($year+20);$y++){
								echo "<option ".(($course->year == $y) ? "selected='selected'" : "")." value=".$y.">".$y."</option>";
							}
							?>
						</select>
					</div>
				</div>
			</div>
			<div style="clear:both; padding-top: 20px">
				<h3>Course Description</h3>
				<div class="form-table">
					<?php
						$args = array("textarea_name" => "course_description");
						wp_editor( $course->description, "course_description", $args );
					?>
				</div>
			</div>
			<p class="submit">
			<input type="submit" class="button-primary" value="<?php _e('Save Changes') ?>" />
			</p>
		</form>
	  </div>
	<?php
}

function edit_course_POST() {
	if (isset($_POST['course_id'])) {
		global $woodb;
		if ($woodb->updateCourse($_POST['course_id'], $_POST['course_title'], $_POST['course_description'], $_POST['course_semester'], intval($_POST['course_year']))) {
			edit_course_GET($_POST['course_id']);
			?><div class="updated below-h2" id="message"><p>Course updated</p></div><?php
		} else {
			edit_course_GET($_POST['course_id']);
			?><div class="error below-h2" id="error"><p>Invalid inputs</p></div><?php
		}
	}
}

?>